/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.controller;

import javax.el.ValueExpression;
import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import offset.nodes.server.model.UserInfo;
import offset.nodes.client.model.HttpUtils;
import offset.nodes.server.error.model.ErrorHandler;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author Walter Lütgenau
 */
public abstract class AuthenticatingAction extends Action {
    private Session repositorySession = null;
    
    /** Creates a new instance of AuthenticatingAction */
    public AuthenticatingAction() {
    }
    
    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception {
        if ( getRepositorySession(request) == null) {
            String info = request.getPathInfo();
            String path = request.getServletPath();
            if ( info != null)
                path = path + "/" + info;
            
            ActionForward loginForward = new ActionForward(path);
            request.getSession().setAttribute( AttributeConstants.ATT_LOGIN_FORWARD, loginForward);
            
            return mapping.findForward( "login");
        }
        
        ActionForward result = null;
        ActionMessages messages = new ActionMessages();
        
        try {
            result = process( mapping, form, request, response );
        } catch(Exception e) {
            ErrorHandler.processException(request, e);
            return mapping.findForward("error");
      }
        
        if ( messages.size() > 0)
            saveMessages(request, messages);
        
        return result;
    }

    public abstract ActionForward process( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception;
    
    public Session getRepositorySession(HttpServletRequest request) {
        return (Session) request.getSession().getAttribute(AttributeConstants.ATT_REPOSITORY_SESSION);
    }
    
    public UserInfo getUserInfo(HttpServletRequest request) {
        return (UserInfo) request.getSession().getAttribute(AttributeConstants.ATT_USER_INFO);
    }
    
    /**
     * Add a parameter to the path represented by the forward and return it as an action forward
     * 
     * @param forward
     * @param key The key of the parameter
     * @param value The value of the parameter
     * @return The resulting ActionForward
     */
    protected ActionForward addParameter( ActionForward forward, String key, String value ) {
        String path = forward.getPath();
        path = HttpUtils.addParameter(path, key, value);
        return new ActionForward(path);
    }
    
   protected Object getBean(HttpServletRequest request, HttpServletResponse response, String valueExpression, Class<?> valueType) {
        FacesContext facesContext = getFacesContext(request, response);
        // create value expression
        ValueExpression expression = facesContext.getApplication().getExpressionFactory().createValueExpression(
            facesContext.getELContext(), valueExpression, valueType);
        // evaluate expression and return the resulting value
        return expression.getValue(facesContext.getELContext());
    }
    
    protected FacesContext getFacesContext(
        HttpServletRequest request, HttpServletResponse response)
    {
        // Get current FacesContext.
        FacesContext facesContext = FacesContext.getCurrentInstance();

        // Check current FacesContext.
        if (facesContext == null) {

            // Create new Lifecycle.
            LifecycleFactory lifecycleFactory = (LifecycleFactory)
                FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); 
            Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

            // Create new FacesContext.
            FacesContextFactory contextFactory  = (FacesContextFactory)
                FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
            facesContext = contextFactory.getFacesContext(
                request.getSession().getServletContext(), request, response, lifecycle);

            // Create new View.
            UIViewRoot view = facesContext.getApplication().getViewHandler().createView(
                facesContext, "");
            facesContext.setViewRoot(view);                

            // Set current FacesContext.
            FacesContextWrapper.setCurrentInstance(facesContext);
        }

        return facesContext;
    }

    // Helpers -----------------------------------------------------------------------------------

    // Wrap the protected FacesContext.setCurrentInstance() in a inner class.
    private static abstract class FacesContextWrapper extends FacesContext {
        protected static void setCurrentInstance(FacesContext facesContext) {
            FacesContext.setCurrentInstance(facesContext);
        }
    }     

    
    
 }
